package com.example.myapplication.frags;

import static android.content.ContentValues.TAG;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.myapplication.data.MessageEvent;
import com.example.myapplication.module_notification.SearchResult;
import com.example.myapplication.R;
import com.example.myapplication.module_notification.ShouYeFragment;
import com.example.myapplication.data.NewsTypes;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 主页，展示各种类别的通知和下面的条目
 * 就一个功能：请求url、然后动态创建不同的fragment
 * 很多代码都是为了绑定 tabbar 和 pageviewer
 */
public class Notification_Fragment extends Fragment {

    private TabLayout tabbar;
    private ViewPager vp;

    private List<NewsTypes> tabs = new ArrayList<>();

    private List<ShouYeFragment> shouYeFragmentList = new ArrayList<>();
    private int currentSelect;
    private TabViewPagerAdapter mAdapter;
    private Handler handler;

    public Notification_Fragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    @SuppressLint("HandlerLeak")
    public static Notification_Fragment newInstance() {
        Notification_Fragment fragment = new Notification_Fragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @SuppressLint("HandlerLeak")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        for (NewsTypes newsTypes : (List<NewsTypes>) msg.obj) {
                            tabs.add(newsTypes);
                            tabbar.addTab(tabbar.newTab().setText(newsTypes.getTypeName()));
                            shouYeFragmentList.add(ShouYeFragment.newInstance(newsTypes.getTypeName(), newsTypes.getId(), newsTypes.getTotal()));
                        }
                        mAdapter = new TabViewPagerAdapter(getActivity().getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, shouYeFragmentList, tabs);

                        vp.setAdapter(mAdapter);
                        vp.setOffscreenPageLimit(shouYeFragmentList.size());
                        vp.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabbar));
                        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                            @Override
                            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                                Log.e(TAG, "onPageScrolled: " + position);
                            }

                            @Override
                            public void onPageSelected(int position) {
                                currentSelect = position;
                            }

                            @Override
                            public void onPageScrollStateChanged(int state) {
                            }
                        });
                        tabbar.setupWithViewPager(vp);
                        tabbar.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                            @Override
                            public void onTabSelected(TabLayout.Tab tab) {
                                vp.setCurrentItem(tab.getPosition(), false);

                            }

                            @Override
                            public void onTabUnselected(TabLayout.Tab tab) {

                            }

                            @Override
                            public void onTabReselected(TabLayout.Tab tab) {

                            }
                        });

                        if (vp.getAdapter() instanceof TabViewPagerAdapter) {
                            //源数据有变更后，要及时更新
                            ((TabViewPagerAdapter) vp.getAdapter()).updateFragmentList(shouYeFragmentList);
                        }
                        //再选中tab变更之前的tab
                        vp.post(new Runnable() {
                            @Override
                            public void run() {
                                tabbar.selectTab(tabbar.getTabAt(currentSelect));
                            }
                        });
                        break;
                }
            }
        };
        getAllNewsTypes();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        tabbar = view.findViewById(R.id.tabs);
        vp = view.findViewById(R.id.news_vp);
        tabbar.setTabMode(TabLayout.MODE_SCROLLABLE);

        ImageView search = view.findViewById(R.id.search_btn);

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(getActivity(), SearchResult.class);
                Log.e(TAG, "onClick: Go To Search");
                startActivity(i);
            }
        });

        return view;
    }

    //http获取全部类别
    private void getAllNewsTypes() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //创建OkHttpClient对象
                    OkHttpClient client = new OkHttpClient();
                    //创建Request// 注意，调试时候模拟器访问电脑用10.0.2.2....

                    Request request = new Request.Builder()
                            .url(getString(R.string.httpPrefix)+"/newsTypes")//访问连接
                            .get()
                            .build();
                    //创建Call对象
                    Call call = client.newCall(request);
                    Gson gson = new Gson();
                    //通过execute()方法获得请求响应的Response对象
                    Response response = call.execute();
                    if (response.isSuccessful()) {
                        ResponseBody body = response.body();
                        String string = body.string();
                        List<NewsTypes> list = gson.fromJson(string, new TypeToken<List<NewsTypes>>() {
                        }.getType());
                        Message message = new Message();
                        message.what = 1;
                        message.obj = list;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    Log.d(TAG, "run: errrrrrrrrrrrrrrrrrrr");
                    e.printStackTrace();
                }
            }
        }).start();

    }


    private class TabViewPagerAdapter extends FragmentPagerAdapter {
        private FragmentManager mFragmentManager;
        private List<ShouYeFragment> mFragmentList = new ArrayList<>();
        private List<NewsTypes> tabItems = new ArrayList<>();

        public TabViewPagerAdapter(@NonNull FragmentManager fm, int behavior, List<ShouYeFragment> fragmentList, List<NewsTypes> tabItems) {
            super(fm, behavior);
            mFragmentManager = fm;
            this.tabItems = tabItems;
            updateFragmentList(fragmentList);
        }

        //将每一个item的id指定为fragment的hasCode，确保不会变更
        @Override
        public long getItemId(int position) {
            return mFragmentList.get(position).hashCode();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return this.tabItems.get(position).getTypeName();
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            Fragment instantiateItemFragment = (Fragment) super.instantiateItem(container, position);
            Fragment itemFragment = mFragmentList.get(position);
            //如果集合中对应下标的fragment和fragmentManager中的对应下标的fragment对象一致，则直接返回该fragment
            if (instantiateItemFragment == itemFragment) {
                return instantiateItemFragment;
            } else {
                //如果集合中对应下标的fragment和fragmentManager中的对应下标的fragment对象不一致，那么就是新添加的，所以自己add进入；
                mFragmentManager.beginTransaction().add(container.getId(), itemFragment).commit();
                return itemFragment;
            }
        }


        @Override
        public int getItemPosition(@NonNull Object object) {
            //如果fragment还没有添加过，或者没有包含在里面，则返回没有找到
            if (!((Fragment) object).isAdded() || !mFragmentList.contains(object)) {
                return POSITION_NONE;
            }
            //否则就返回列表中的位置
            return mFragmentList.indexOf(object);
        }


        public void updateFragmentList(List<ShouYeFragment> fragmentList) {
            if (!mFragmentList.isEmpty()) {
                mFragmentList.clear();
            }
            mFragmentList.addAll(fragmentList);
            notifyDataSetChanged();
            vp.setOffscreenPageLimit(mFragmentList.size());
        }


        @NonNull
        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        Log.d("notification", "onMessageEvent: "+event.getMessage());
    }
}